<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Traits\ValidationTrait;
use Exception;
use Illuminate\Http\Request;

/**
 * 密码相关
 */
class PasswordController extends Controller
{
    use ValidationTrait;
    /**
     * 修改登录密码
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function modify_password(Request $request)
    {
        try {
            $status = 0;
            //验证
            $validator = $this->verify($request, 'validation.modify_password');
            if ($validator->fails()) {
                $messages = $validator->messages()->first();

                throw new Exception($messages);
            }
            $password = $request->get('password');
            $repass   = $request->get('repass');
            $code     = $request->get('code');
            $userID   = $request->get('user_id');
            $user     = User::where(['userID' => $userID])->first();
            if ($password != $repass) {
                throw new Exception('两次密码不一致');
            }
            $password = md5($password . config('public.password_key'));
            if ($user->password == $password) {
                throw new Exception('新密码不能与原密码相同！');
            }
            $sms = Sms::where(['phone' => $user->phone, 'type' => 1])->first();
            //验证码过期
            if (time() > $sms->expired_at) {
                return respF('验证码已过期！');
            }
            //验证码错误
            if ($sms->code != $code) {
                return respF('验证码错误！');
            }
            $user->update([
                'password' => $password,
            ]);

            $status = 1;
            $msg    = '操作成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg]);
    }
}
